home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / perl5 / DateTime / Duration.pm next >
Encoding:
Perl POD Document  |  2010-07-30  |  17.2 KB  |  628 lines

  1. package DateTime::Duration;
  2. BEGIN {
  3.   $DateTime::Duration::VERSION = '0.61';
  4. }
  5.  
  6. use strict;
  7. use warnings;
  8.  
  9. use Carp ();
  10. use DateTime;
  11. use DateTime::Helpers;
  12. use Params::Validate qw( validate SCALAR );
  13.  
  14. use overload (
  15.     fallback => 1,
  16.     '+'      => '_add_overload',
  17.     '-'      => '_subtract_overload',
  18.     '*'      => '_multiply_overload',
  19.     '<=>'    => '_compare_overload',
  20.     'cmp'    => '_compare_overload',
  21. );
  22.  
  23. use constant MAX_NANOSECONDS => 1_000_000_000;    # 1E9 = almost 32 bits
  24.  
  25. my @all_units = qw( months days minutes seconds nanoseconds );
  26.  
  27. # XXX - need to reject non-integers but accept infinity, NaN, &
  28. # 1.56e+18
  29. sub new {
  30.     my $class = shift;
  31.     my %p     = validate(
  32.         @_, {
  33.             years        => { type => SCALAR, default => 0 },
  34.             months       => { type => SCALAR, default => 0 },
  35.             weeks        => { type => SCALAR, default => 0 },
  36.             days         => { type => SCALAR, default => 0 },
  37.             hours        => { type => SCALAR, default => 0 },
  38.             minutes      => { type => SCALAR, default => 0 },
  39.             seconds      => { type => SCALAR, default => 0 },
  40.             nanoseconds  => { type => SCALAR, default => 0 },
  41.             end_of_month => {
  42.                 type  => SCALAR, default => undef,
  43.                 regex => qr/^(?:wrap|limit|preserve)$/
  44.             },
  45.         }
  46.     );
  47.  
  48.     my $self = bless {}, $class;
  49.  
  50.     $self->{months} = ( $p{years} * 12 ) + $p{months};
  51.  
  52.     $self->{days} = ( $p{weeks} * 7 ) + $p{days};
  53.  
  54.     $self->{minutes} = ( $p{hours} * 60 ) + $p{minutes};
  55.  
  56.     $self->{seconds} = $p{seconds};
  57.  
  58.     if ( $p{nanoseconds} ) {
  59.         $self->{nanoseconds} = $p{nanoseconds};
  60.         $self->_normalize_nanoseconds;
  61.     }
  62.     else {
  63.  
  64.         # shortcut - if they don't need nanoseconds
  65.         $self->{nanoseconds} = 0;
  66.     }
  67.  
  68.     $self->{end_of_month} = (
  69.           defined $p{end_of_month} ? $p{end_of_month}
  70.         : $self->{months} < 0      ? 'preserve'
  71.         : 'wrap'
  72.     );
  73.  
  74.     return $self;
  75. }
  76.  
  77. # make the signs of seconds, nanos the same; 0 < abs(nanos) < MAX_NANOS
  78. # NB this requires nanoseconds != 0 (callers check this already)
  79. sub _normalize_nanoseconds {
  80.     my $self = shift;
  81.  
  82.     return
  83.         if ( $self->{nanoseconds} == DateTime::INFINITY()
  84.         || $self->{nanoseconds} == DateTime::NEG_INFINITY()
  85.         || $self->{nanoseconds} eq DateTime::NAN() );
  86.  
  87.     my $seconds = $self->{seconds} + $self->{nanoseconds} / MAX_NANOSECONDS;
  88.     $self->{seconds}     = int($seconds);
  89.     $self->{nanoseconds} = $self->{nanoseconds} % MAX_NANOSECONDS;
  90.     $self->{nanoseconds} -= MAX_NANOSECONDS if $seconds < 0;
  91. }
  92.  
  93. sub clone { bless { %{ $_[0] } }, ref $_[0] }
  94.  
  95. sub years       { abs( $_[0]->in_units('years') ) }
  96. sub months      { abs( $_[0]->in_units( 'months', 'years' ) ) }
  97. sub weeks       { abs( $_[0]->in_units('weeks') ) }
  98. sub days        { abs( $_[0]->in_units( 'days', 'weeks' ) ) }
  99. sub hours       { abs( $_[0]->in_units('hours') ) }
  100. sub minutes     { abs( $_[0]->in_units( 'minutes', 'hours' ) ) }
  101. sub seconds     { abs( $_[0]->in_units('seconds') ) }
  102. sub nanoseconds { abs( $_[0]->in_units( 'nanoseconds', 'seconds' ) ) }
  103.  
  104. sub is_positive { $_[0]->_has_positive  && !$_[0]->_has_negative }
  105. sub is_negative { !$_[0]->_has_positive && $_[0]->_has_negative }
  106.  
  107. sub _has_positive {
  108.     ( grep { $_ > 0 } @{ $_[0] }{@all_units} ) ? 1 : 0;
  109. }
  110.  
  111. sub _has_negative {
  112.     ( grep { $_ < 0 } @{ $_[0] }{@all_units} ) ? 1 : 0;
  113. }
  114.  
  115. sub is_zero {
  116.     return 0 if grep { $_ != 0 } @{ $_[0] }{@all_units};
  117.     return 1;
  118. }
  119.  
  120. sub delta_months      { $_[0]->{months} }
  121. sub delta_days        { $_[0]->{days} }
  122. sub delta_minutes     { $_[0]->{minutes} }
  123. sub delta_seconds     { $_[0]->{seconds} }
  124. sub delta_nanoseconds { $_[0]->{nanoseconds} }
  125.  
  126. sub deltas {
  127.     map { $_ => $_[0]->{$_} } @all_units;
  128. }
  129.  
  130. sub in_units {
  131.     my $self  = shift;
  132.     my @units = @_;
  133.  
  134.     my %units = map { $_ => 1 } @units;
  135.  
  136.     my %ret;
  137.  
  138.     my ( $months, $days, $minutes, $seconds )
  139.         = @{$self}{qw( months days minutes seconds )};
  140.  
  141.     if ( $units{years} ) {
  142.         $ret{years} = int( $months / 12 );
  143.         $months -= $ret{years} * 12;
  144.     }
  145.  
  146.     if ( $units{months} ) {
  147.         $ret{months} = $months;
  148.     }
  149.  
  150.     if ( $units{weeks} ) {
  151.         $ret{weeks} = int( $days / 7 );
  152.         $days -= $ret{weeks} * 7;
  153.     }
  154.  
  155.     if ( $units{days} ) {
  156.         $ret{days} = $days;
  157.     }
  158.  
  159.     if ( $units{hours} ) {
  160.         $ret{hours} = int( $minutes / 60 );
  161.         $minutes -= $ret{hours} * 60;
  162.     }
  163.  
  164.     if ( $units{minutes} ) {
  165.         $ret{minutes} = $minutes;
  166.     }
  167.  
  168.     if ( $units{seconds} ) {
  169.         $ret{seconds} = $seconds;
  170.         $seconds = 0;
  171.     }
  172.  
  173.     if ( $units{nanoseconds} ) {
  174.         $ret{nanoseconds} = $seconds * MAX_NANOSECONDS + $self->{nanoseconds};
  175.     }
  176.  
  177.     wantarray ? @ret{@units} : $ret{ $units[0] };
  178. }
  179.  
  180. sub is_wrap_mode     { $_[0]->{end_of_month} eq 'wrap'     ? 1 : 0 }
  181. sub is_limit_mode    { $_[0]->{end_of_month} eq 'limit'    ? 1 : 0 }
  182. sub is_preserve_mode { $_[0]->{end_of_month} eq 'preserve' ? 1 : 0 }
  183.  
  184. sub end_of_month_mode { $_[0]->{end_of_month} }
  185.  
  186. sub calendar_duration {
  187.     my $self = shift;
  188.  
  189.     return ( ref $self )
  190.         ->new( map { $_ => $self->{$_} } qw( months days end_of_month ) );
  191. }
  192.  
  193. sub clock_duration {
  194.     my $self = shift;
  195.  
  196.     return ( ref $self )
  197.         ->new( map { $_ => $self->{$_} }
  198.             qw( minutes seconds nanoseconds end_of_month ) );
  199. }
  200.  
  201. sub inverse {
  202.     my $self = shift;
  203.     my %p    = @_;
  204.  
  205.     my %new;
  206.     foreach my $u (@all_units) {
  207.         $new{$u} = $self->{$u};
  208.  
  209.         # avoid -0 bug
  210.         $new{$u} *= -1 if $new{$u};
  211.     }
  212.  
  213.     $new{end_of_month} = $p{end_of_month}
  214.         if exists $p{end_of_month};
  215.  
  216.     return ( ref $self )->new(%new);
  217. }
  218.  
  219. sub add_duration {
  220.     my ( $self, $dur ) = @_;
  221.  
  222.     foreach my $u (@all_units) {
  223.         $self->{$u} += $dur->{$u};
  224.     }
  225.  
  226.     $self->_normalize_nanoseconds if $self->{nanoseconds};
  227.  
  228.     return $self;
  229. }
  230.  
  231. sub add {
  232.     my $self = shift;
  233.  
  234.     return $self->add_duration( ( ref $self )->new(@_) );
  235. }
  236.  
  237. sub subtract_duration { return $_[0]->add_duration( $_[1]->inverse ) }
  238.  
  239. sub subtract {
  240.     my $self = shift;
  241.  
  242.     return $self->subtract_duration( ( ref $self )->new(@_) );
  243. }
  244.  
  245. sub multiply {
  246.     my $self       = shift;
  247.     my $multiplier = shift;
  248.  
  249.     foreach my $u (@all_units) {
  250.         $self->{$u} *= $multiplier;
  251.     }
  252.  
  253.     $self->_normalize_nanoseconds if $self->{nanoseconds};
  254.  
  255.     return $self;
  256. }
  257.  
  258. sub compare {
  259.     my ( $class, $dur1, $dur2, $dt ) = @_;
  260.  
  261.     $dt ||= DateTime->now;
  262.  
  263.     return DateTime->compare( $dt->clone->add_duration($dur1),
  264.         $dt->clone->add_duration($dur2) );
  265. }
  266.  
  267. sub _add_overload {
  268.     my ( $d1, $d2, $rev ) = @_;
  269.  
  270.     ( $d1, $d2 ) = ( $d2, $d1 ) if $rev;
  271.  
  272.     if ( DateTime::Helpers::isa( $d2, 'DateTime' ) ) {
  273.         $d2->add_duration($d1);
  274.         return;
  275.     }
  276.  
  277.     # will also work if $d1 is a DateTime.pm object
  278.     return $d1->clone->add_duration($d2);
  279. }
  280.  
  281. sub _subtract_overload {
  282.     my ( $d1, $d2, $rev ) = @_;
  283.  
  284.     ( $d1, $d2 ) = ( $d2, $d1 ) if $rev;
  285.  
  286.     Carp::croak(
  287.         "Cannot subtract a DateTime object from a DateTime::Duration object")
  288.         if DateTime::Helpers::isa( $d2, 'DateTime' );
  289.  
  290.     return $d1->clone->subtract_duration($d2);
  291. }
  292.  
  293. sub _multiply_overload {
  294.     my $self = shift;
  295.  
  296.     my $new = $self->clone;
  297.  
  298.     return $new->multiply(@_);
  299. }
  300.  
  301. sub _compare_overload {
  302.     Carp::croak( 'DateTime::Duration does not overload comparison.'
  303.             . '  See the documentation on the compare() method for details.'
  304.     );
  305. }
  306.  
  307. 1;
  308.  
  309. # ABSTRACT: Duration objects for date math
  310.  
  311.  
  312.  
  313. =pod
  314.  
  315. =head1 NAME
  316.  
  317. DateTime::Duration - Duration objects for date math
  318.  
  319. =head1 VERSION
  320.  
  321. version 0.61
  322.  
  323. =head1 SYNOPSIS
  324.  
  325.   use DateTime::Duration;
  326.  
  327.   $d = DateTime::Duration->new( years   => 3,
  328.                                 months  => 5,
  329.                                 weeks   => 1,
  330.                                 days    => 1,
  331.                                 hours   => 6,
  332.                                 minutes => 15,
  333.                                 seconds => 45,
  334.                                 nanoseconds => 12000 );
  335.  
  336.   # Convert to different units
  337.   $d->in_units('days', 'hours', 'seconds');
  338.  
  339.   # The important parts for date math
  340.   $d->delta_months
  341.   $d->delta_days
  342.   $d->delta_minutes
  343.   $d->delta_seconds
  344.   $d->delta_nanoseconds
  345.  
  346.   my %deltas = $d->deltas
  347.  
  348.   $d->is_wrap_mode
  349.   $d->is_limit_mode
  350.   $d->is_preserve_mode
  351.  
  352.   print $d->end_of_month_mode;
  353.  
  354.   # Multiple all deltas by -1
  355.   my $opposite = $d->inverse;
  356.  
  357.   my $bigger  = $dur1 + $dur2;
  358.   my $smaller = $dur1 - $dur2; # the result could be negative
  359.   my $bigger  = $dur1 * 3;
  360.  
  361.   my $base_dt = DateTime->new( year => 2000 );
  362.   my @sorted =
  363.       sort { DateTime::Duration->compare( $a, $b, $base_dt ) } @durations;
  364.  
  365.   # Human-readable accessors, always positive, but use
  366.   # DateTime::Format::Duration instead
  367.   $d->years;
  368.   $d->months;
  369.   $d->weeks;
  370.   $d->days;
  371.   $d->hours;
  372.   $d->minutes;
  373.   $d->seconds;
  374.   $d->nanoseconds;
  375.  
  376.   if ( $d->is_positive ) { ... }
  377.   if ( $d->is_zero )     { ... }
  378.   if ( $d->is_negative ) { ... }
  379.  
  380. =head1 DESCRIPTION
  381.  
  382. This is a simple class for representing duration objects.  These
  383. objects are used whenever you do date math with DateTime.pm.
  384.  
  385. See the L<How Date Math is Done|DateTime/"How Date Math is Done">
  386. section of the DateTime.pm documentation for more details.  The short
  387. course:  One cannot in general convert between seconds, minutes, days,
  388. and months, so this class will never do so.  Instead, create the
  389. duration with the desired units to begin with, for example by calling
  390. the appropriate subtraction/delta method on a C<DateTime.pm> object.
  391.  
  392. =head1 METHODS
  393.  
  394. Like C<DateTime> itself, C<DateTime::Duration> returns the object from
  395. mutator methods in order to make method chaining possible.
  396.  
  397. C<DateTime::Duration> has the following methods:
  398.  
  399. =over 4
  400.  
  401. =item * new( ... )
  402.  
  403. This method takes the parameters "years", "months", "weeks", "days",
  404. "hours", "minutes", "seconds", "nanoseconds", and "end_of_month".  All
  405. of these except "end_of_month" are numbers.  If any of the numbers are
  406. negative, the entire duration is negative.
  407.  
  408. All of the numbers B<must be integers>.
  409.  
  410. Internally, years as just treated as 12 months.  Similarly, weeks are
  411. treated as 7 days, and hours are converted to minutes.  Seconds and
  412. nanoseconds are both treated separately.
  413.  
  414. The "end_of_month" parameter must be either "wrap", "limit", or
  415. "preserve".  This parameter specifies how date math that crosses the
  416. end of a month is handled.
  417.  
  418. In "wrap" mode, adding months or years that result in days beyond the
  419. end of the new month will roll over into the following month.  For
  420. instance, adding one year to Feb 29 will result in Mar 1.
  421.  
  422. If you specify "end_of_month" mode as "limit", the end of the month is
  423. never crossed.  Thus, adding one year to Feb 29, 2000 will result in
  424. Feb 28, 2001.  If you were to then add three more years this will
  425. result in Feb 28, 2004.
  426.  
  427. If you specify "end_of_month" mode as "preserve", the same calculation
  428. is done as for "limit" except that if the original date is at the end
  429. of the month the new date will also be.  For instance, adding one
  430. month to Feb 29, 2000 will result in Mar 31, 2000.
  431.  
  432. For positive durations, the "end_of_month" parameter defaults to wrap.
  433. For negative durations, the default is "limit".  This should match how
  434. most people "intuitively" expect datetime math to work.
  435.  
  436. =item * clone
  437.  
  438. Returns a new object with the same properties as the object on which
  439. this method was called.
  440.  
  441. =item * in_units( ... )
  442.  
  443. Returns the length of the duration in the units (any of those that can
  444. be passed to L<new>) given as arguments.  All lengths are integral,
  445. but may be negative.  Smaller units are computed from what remains
  446. after taking away the larger units given, so for example:
  447.  
  448.   my $dur = DateTime::Duration->new( years => 1, months => 15 );
  449.  
  450.   $dur->in_units( 'years' );            # 2
  451.   $dur->in_units( 'months' );           # 27
  452.   $dur->in_units( 'years', 'months' );  # (2, 3)
  453.   $dur->in_units( 'weeks', 'days' );    # (0, 0) !
  454.  
  455. The last example demonstrates that there will not be any conversion
  456. between units which don't have a fixed conversion rate.  The only
  457. conversions possible are:
  458.  
  459. =over 8
  460.  
  461. =item * years <=> months
  462.  
  463. =item * weeks <=> days
  464.  
  465. =item * hours <=> minutes
  466.  
  467. =item * seconds <=> nanoseconds
  468.  
  469. =back
  470.  
  471. For the explanation of why this happens, please see the L<How Date
  472. Math is Done|DateTime/"How Date Math is Done"> section of the
  473. DateTime.pm documentation
  474.  
  475. Note that the numbers returned by this method may not match the values
  476. given to the constructor.
  477.  
  478. In list context, in_units returns the lengths in the order of the units
  479. given.  In scalar context, it returns the length in the first unit (but
  480. still computes in terms of all given units).
  481.  
  482. If you need more flexibility in presenting information about
  483. durations, please take a look a C<DateTime::Format::Duration>.
  484.  
  485. =item * delta_months, delta_days, delta_minutes, delta_seconds, delta_nanoseconds
  486.  
  487. These methods provide the information C<DateTime.pm> needs for doing
  488. date math.  The numbers returned may be positive or negative.
  489.  
  490. =item * deltas
  491.  
  492. Returns a hash with the keys "months", "days", "minutes", "seconds",
  493. and "nanoseconds", containing all the delta information for the
  494. object.
  495.  
  496. =item * is_positive, is_zero, is_negative
  497.  
  498. Indicates whether or not the duration is positive, zero, or negative.
  499.  
  500. If the duration contains both positive and negative units, then it
  501. will return false for B<all> of these methods.
  502.  
  503. =item * is_wrap_mode, is_limit_mode, is_preserve_mode
  504.  
  505. Indicates what mode is used for end of month wrapping.
  506.  
  507. =item * end_of_month_mode
  508.  
  509. Returns one of "wrap", "limit", or "preserve".
  510.  
  511. =item * calendar_duration
  512.  
  513. Returns a new object with the same I<calendar> delta (months and days
  514. only) and end of month mode as the current object.
  515.  
  516. =item * clock_duration
  517.  
  518. Returns a new object with the same I<clock> deltas (minutes, seconds,
  519. and nanoseconds) and end of month mode as the current object.
  520.  
  521. =item * inverse( ... )
  522.  
  523. Returns a new object with the same deltas as the current object, but
  524. multiple by -1.  The end of month mode for the new object will be the
  525. default end of month mode, which depends on whether the new duration
  526. is positive or negative.
  527.  
  528. You can set the end of month mode in the inverted duration explicitly by
  529. passing "end_of_month => ..." to the C<inverse()> method.
  530.  
  531. =item * add_duration( $duration_object ), subtract_duration( $duration_object )
  532.  
  533. Adds or subtracts one duration from another.
  534.  
  535. =item * add( ... ), subtract( ... )
  536.  
  537. Syntactic sugar for addition and subtraction.  The parameters given to
  538. these methods are used to create a new object, which is then passed to
  539. C<add_duration()> or C<subtract_duration()>, as appropriate.
  540.  
  541. =item * multiply( $number )
  542.  
  543. Multiplies each unit in the by the specified number.
  544.  
  545. =item * DateTime::Duration->compare( $duration1, $duration2, $base_datetime )
  546.  
  547. This is a class method that can be used to compare or sort durations.
  548. Comparison is done by adding each duration to the specified
  549. C<DateTime.pm> object and comparing the resulting datetimes.  This is
  550. necessary because without a base, many durations are not comparable.
  551. For example, 1 month may or may not be longer than 29 days, depending
  552. on what datetime it is added to.
  553.  
  554. If no base datetime is given, then the result of C<< DateTime->now >>
  555. is used instead.  Using this default will give non-repeatable results
  556. if used to compare two duration objects containing different units.
  557. It will also give non-repeatable results if the durations contain
  558. multiple types of units, such as months and days.
  559.  
  560. However, if you know that both objects only consist of one type of
  561. unit (months I<or> days I<or> hours, etc.), and each duration contains
  562. the same type of unit, then the results of the comparison will be
  563. repeatable.
  564.  
  565. =item * years, months, weeks, days, hours, minutes, seconds, nanoseconds
  566.  
  567. These methods return numbers indicating how many of the given unit the
  568. object represents, after having done a conversion to any larger units.
  569. For example, days are first converted to weeks, and then the remainder
  570. is returned.  These numbers are always positive.
  571.  
  572. Here's what each method returns:
  573.  
  574.  $dur->years()       == abs( $dur->in_units('years') )
  575.  $dur->months()      == abs( ( $dur->in_units( 'months', 'years' ) )[0] )
  576.  $dur->weeks()       == abs( $dur->in_units( 'weeks' ) )
  577.  $dur->days()        == abs( ( $dur->in_units( 'days', 'weeks' ) )[0] )
  578.  $dur->hours()       == abs( $dur->in_units( 'hours' ) )
  579.  $dur->minutes       == abs( ( $dur->in_units( 'minutes', 'hours' ) )[0] )
  580.  $dur->seconds       == abs( $dur->in_units( 'seconds' ) )
  581.  $dur->nanoseconds() == abs( ( $dur->in_units( 'nanoseconds', 'seconds' ) )[0] )
  582.  
  583. If this seems confusing, remember that you can always use the
  584. C<in_units()> method to specify exactly what you want.
  585.  
  586. Better yet, if you are trying to generate output suitable for humans,
  587. use the C<DateTime::Format::Duration> module.
  588.  
  589. =back
  590.  
  591. =head2 Overloading
  592.  
  593. This class overloads addition, subtraction, and mutiplication.
  594.  
  595. Comparison is B<not> overloaded.  If you attempt to compare durations
  596. using C<< <=> >> or C<cmp>, then an exception will be thrown!  Use the
  597. C<compare()> class method instead.
  598.  
  599. =head1 SUPPORT
  600.  
  601. Support for this module is provided via the datetime@perl.org email
  602. list.  See http://lists.perl.org/ for more details.
  603.  
  604. =head1 SEE ALSO
  605.  
  606. datetime@perl.org mailing list
  607.  
  608. http://datetime.perl.org/
  609.  
  610. =head1 AUTHOR
  611.  
  612. Dave Rolsky <autarch@urth.org>
  613.  
  614. =head1 COPYRIGHT AND LICENSE
  615.  
  616. This software is Copyright (c) 2010 by Dave Rolsky.
  617.  
  618. This is free software, licensed under:
  619.  
  620.   The Artistic License 2.0
  621.  
  622. =cut
  623.  
  624.  
  625. __END__
  626.  
  627.  
  628.